package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.yh.common.utils.ExcelUtil;
import com.yh.correct.model.CorrectedPerson;
import com.yh.correct.model.JudicialDeptment;
import com.yh.correct.model.MovePersonelHelpClass;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.service.IMovePersonnelService;

/**
 * 居住地变更控制层
 *
 */

@RestController
@RequestMapping("/movePersonel")
@PropertySource(value = "classpath:config/system.properties")
public class MovePersonnelController {
	/**
	 * 日志记录
	 */
	private static Logger logger = LogManager.getLogger(MovePersonnelController.class);
	/**
	 * 注入居住地变更服务
	 */
	@Autowired
	private IMovePersonnelService movePersonnelservice;

	/**
	 * 首页面
	 */
	@RequestMapping("showMain")
	public ModelAndView showMain() {
		Map<String, Object> map = new HashMap<String, Object>();
		List<JudicialDeptment> list = null;
		try {
			list = movePersonnelservice.findAllJudicialDeptment();
			map.put("list", list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView("supervision/movePersonel", map);
	}
	/**
	 * 模糊查询 查询条件 分页查询
	 */
	@RequestMapping(value = "/findList", method = RequestMethod.GET)
	public Page getLikeMovePersonnel(MovePersonelHelpClass helpClass, String startDate, String endDate) {
		Map<String, Object> map = new HashMap<String, Object>();
		Page page = null;
		try {
			map.put("helpClass", helpClass);
			map.put("curPageNum", helpClass.getCurPageNum());
			map.put("pageSize", helpClass.getPageSize());
			if (!Objects.equals(startDate.trim(), "") && !Objects.equals(endDate.trim(), "")) {
				long sDate = Long.valueOf(startDate.replaceAll("[-\\s:]", ""));
				long eDate = Long.valueOf(endDate.replaceAll("[-\\s:]", ""));
				if (sDate > eDate) {
					startDate = null;
					endDate = null;
				}
			}
			map.put("startDate", startDate);
			map.put("endDate", endDate);
			page = movePersonnelservice.getMovePersonnelByPage(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return page;
	}
	/**
	 * 查询服刑人员详情
	 */
	@RequestMapping("/checkDetail")
	public ModelAndView getDetail(int id) {
		//logger.info(id);
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map.put("movePersonnelDetail", movePersonnelservice.getDetail(id));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView("supervision/movePersonel_check", map);
	}
	/**
	 * 编辑服刑人员信息
	 */
	@RequestMapping("/edit")
	public ModelAndView edit(int id) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map.put("movePersonnelDetail", movePersonnelservice.getDetail(id));
			map.put("judicialDeptmentList", movePersonnelservice.findAllJudicialDeptment());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView("supervision/movePersonel_edit", map);
	}
	/**
	 * 修改服刑人员信息
	 */
	@Value("${saveDirUpload}") // 上传文件
	private String saveDirUpload;

	@RequestMapping("/update")
	public ResultData update(@Valid MovePersonelHelpClass helpClass, MultipartFile[] file) {
		ResultData rs = new ResultData();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("helpClass", helpClass);
		int i = 0;
		try {
			if (file != null && file.length > 0) {
				for (MultipartFile mf : file) {
					String originalFilename = mf.getOriginalFilename();
					String dir = saveDirUpload + "\\" + originalFilename.substring(0, originalFilename.lastIndexOf("."))
							+ "\\";
					File f = new File(dir);
					if (!f.exists()) {
						f.mkdirs();
					}
					mf.transferTo(new File(dir, originalFilename));
				}
			}
			i = movePersonnelservice.updateMovePersonel(map);
			if (i > 0) {
				rs.setCode(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}
	/**
	 * 删除迁居记录
	 */
	@RequestMapping("/delete")
	public ResultData delete(int id) {
		ResultData rd = new ResultData();
		int i = 0;
		try {
			i = movePersonnelservice.deleteMovePersonelById(id);
			if (i > 0) {
				rd.setCode(0);
				rd.setMessage("删除成功!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rd;
	}
	/**
	 * 跳转保存信息页面
	 */
	@RequestMapping("/preSave")
	public ModelAndView preSave() {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map.put("judicialDeptmentList", movePersonnelservice.findAllJudicialDeptment());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView("supervision/movePersonel_save",map);
	}
	/**
	 * 根据jid查询所有矫正人员
	 */
	@RequestMapping("/getAllCorrectedPerson")
	public ResultData getAllCorrectedPerson(Integer id){
		List<CorrectedPerson> list = new ArrayList<CorrectedPerson>();
		if(id==0){
			return null;
		}
		try {
			list = movePersonnelservice.findCorrectedPersonByJid(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		ResultData rd = new ResultData();
		rd.setData(list);
		return rd;
	}
	/**
	 * 根据cid查询矫正人员
	 */
	@RequestMapping("/getCorrectedPersonDetail")
	public ResultData getCorrectedPersonDetail(int id){
		ResultData rd = new ResultData();
		List<Object> list = null;
		try {
			list = movePersonnelservice.getDetail(id);
			rd.setData(list);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//logger.debug(list);
		return rd;
	}
	/**
	 * 保存迁居登记信息
	 */
	@RequestMapping("/save")
	public ResultData save(@Valid MovePersonelHelpClass helpClass) {
		ResultData rd = new ResultData();
		Map<String,Object> map = new HashMap<String,Object>();
		int i = 0;
		try {
			map.put("helpClass", helpClass);
			i = movePersonnelservice.addMovePersonelMessage(map);
			if(i>0){
				rd.setCode(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rd;
	}
	/**
	 * 导出excel
	 */
	@RequestMapping("/exportExcel")
	public String exportExcel(HttpServletResponse response,int[] ids){
		//logger.debug(ids.length);
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		try {
			if (ids != null && ids.length>0) {
				for (int id : ids) {
					Map<String, Object> map = movePersonnelservice.getMovePersonnelById(id);
					list.add(map);
				}
			} else {
				list = movePersonnelservice.getMovePersonnel();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Map<String,Object>> list1 = createExcelRecord(list);
		String fileName = "迁居记录登记表";
		String columnNames[] = { "序号", "服刑人员","迁居日期",  "工作单位",  "迁居事由", "政治面貌","迁居地址","矫正单位","工作情况","迁居状态","亲属姓名","亲属关系" };// 列名
		String keys[] = { "id", "cname","mdate",  "org",  "reason", "zz_status","mplace","jname","job","status","rname","relation"};// map中的key
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			ExcelUtil.createWorkBook(list1, keys, columnNames).write(os);
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			// 设置response参数，可以打开下载页面
			response.reset();
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
			ServletOutputStream out = response.getOutputStream();
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (IOException e) {
			e.printStackTrace();;
		} finally {
			try{
				if (bis != null)
					bis.close();
				if (bos != null)
					bos.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return "";
	}
	/**
	 * excel辅助方法
	 * j.name as jname,c.name as cname,m.date,m.place,m.reson,c.zz_status as c_zz_status,m.status,m.job,m.org,
		r.relation,r.name as rname
	 */
	private List<Map<String, Object>> createExcelRecord(List<Map<String, Object>> projects) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet1");
		listmap.add(map);
		Map<String, Object> object = null;
		for (int j = 0; j < projects.size(); j++) {
			object = projects.get(j);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("id", j+1);
			mapValue.put("mdate", object.get("date"));
			mapValue.put("rname", object.get("rname"));
			mapValue.put("org", object.get("org"));
			mapValue.put("cname", object.get("cname"));
			mapValue.put("reason", object.get("reson"));
			mapValue.put("zz_status", object.get("c_zz_status"));
			mapValue.put("mplace", object.get("place"));
			mapValue.put("jname", object.get("jname"));
			mapValue.put("job", object.get("job"));
			mapValue.put("status", object.get("status"));
			mapValue.put("relation", object.get("relation"));
			listmap.add(mapValue);
		}
		return listmap;
	}
	/**
	 * 批量删除
	 */
	@RequestMapping("/deleteBatch")
	public ResultData deleteBatch(@RequestParam("ids[]") List<Integer> list){
		ResultData rd = new ResultData();
		int i = 0;
		try {
			i = movePersonnelservice.deleteBatch(list);
			if(i>0){
				rd.setCode(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rd;
	}
}
